package com.fastjrun.share.demo.service.impl;

import com.fastjrun.common.ServiceException;
import com.fastjrun.dto.PageResult;
import com.fastjrun.helper.MockHelper;
import com.fastjrun.share.demo.common.CodeMsgConstants;
import com.fastjrun.share.demo.dao.SysUserDao;
import com.fastjrun.share.demo.dto.ChangePwdDTO;
import com.fastjrun.share.demo.dto.UserDTO;
import com.fastjrun.share.demo.dto.UserQueryDTO;
import com.fastjrun.share.demo.entity.SysUser;
import com.fastjrun.share.demo.entity.SysUserExample;
import com.fastjrun.share.demo.helper.DTOToEntifyConverter;
import com.fastjrun.share.demo.helper.EntityToVOConverter;
import com.fastjrun.share.demo.service.BaseDemoService;
import com.fastjrun.share.demo.service.SysUserManagerService;
import com.fastjrun.share.demo.vo.TotalVO;
import com.fastjrun.share.demo.vo.UserVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;


/**
 * 注意：本内容仅限于公司内部传阅，禁止外泄以及用于其他的商业目的
 *
 * @author cuiyingfeng
 * @Copyright 2021 快嘉. All rights reserved.
 */
@Service("sysUserManagerService")
public class SysUserManagerServiceImpl extends BaseDemoService
        implements SysUserManagerService {

    @Autowired
    SysUserDao sysUserDao;

    @Autowired
    PasswordEncoder passwordEncoder;

    /**
     * 条件分页查询用户列表
     */
    @Override
    public PageResult<UserVO> search(UserQueryDTO requestBody) {
        PageResult<UserVO> response = new PageResult();
        List<UserVO> list = new ArrayList();


        String mobile=requestBody.getMobile();
        String userName=requestBody.getUsername();
        Integer current=requestBody.getCurrent();
        Integer size= requestBody.getSize();

        SysUserExample sysUserExample = new SysUserExample();
        SysUserExample.Criteria criteria = sysUserExample.createCriteria();

        if(mobile!=null&&!mobile.equals("")){
            criteria.andMobileEqualTo(mobile);
        }

        if(userName!=null&&!userName.equals("")){
            if(criteria.getCriteria().size()>0){
                sysUserExample.or().andUsernameLike(userName);
            }
            criteria.andUsernameLike(userName);
        }

        PageHelper.startPage(current, size,true);

        PageInfo<SysUser> pageInfo=new PageInfo<>(sysUserDao.selectByExample(sysUserExample));

        pageInfo.getList().stream().forEach(sysUser -> {
            list.add(EntityToVOConverter.convert(sysUser));
        });

        response.setRows(list);
        response.setCurrPage(current);
        response.setPageSize(size);
        response.setTotalPage(pageInfo.getPages());
        response.setTotal((int)pageInfo.getTotal());
        return response;
    }

    /**
     * 查询用户信息
     */
    @Override
    public UserVO getById(Long id) {
        UserVO userVO0 = new UserVO();
        SysUser sysUser = sysUserDao.selectByPrimaryKey(id);
        return EntityToVOConverter.convert(sysUser);
    }

    /**
     * 新增用户
     */
    @Override
    public void add(UserDTO requestBody) {
        SysUser sysUser = DTOToEntifyConverter.convert(requestBody);
        // 默认用户密码就是用户名
        sysUser.setPassword(requestBody.getUsername());
        Date currentDate=new Date(System.currentTimeMillis());
        sysUser.setCreateDate(currentDate);
        sysUser.setUpdateDate(currentDate);
        sysUser.setIsEnabled(1);
        sysUserDao.insert(sysUser);
    }

    /**
     * 修改用户
     */
    @Override
    public void save(UserDTO requestBody) {
        SysUser sysUser = DTOToEntifyConverter.convert(requestBody);
        Date currentDate=new Date(System.currentTimeMillis());
        sysUser.setUpdateDate(currentDate);
        sysUserDao.updateByPrimaryKeySelective(sysUser);
    }

    /**
     * 删除用户信息
     */
    @Override
    public void deleteById(Long id) {
        sysUserDao.deleteByPrimaryKey(id);
    }

    /**
     * 修改新密码
     */
    @Override
    public void password(ChangePwdDTO requestBody) {
        Long userId = requestBody.getUserId();
        String newPassword = requestBody.getNewPassword();
        String repPassword = requestBody.getRepPassword();
        if (!newPassword.equals(repPassword)) {
            throw new ServiceException(CodeMsgConstants.SYSUSERMANAGERSERVICEIMPL_21003, this.serviceMessageSource.getMessage(CodeMsgConstants.SYSUSERMANAGERSERVICEIMPL_21003, null, null));
        }
        SysUser record = new SysUser();
        record.setId(userId);
        record.setPassword(passwordEncoder.encode(newPassword));
        Date currentDate=new Date(System.currentTimeMillis());
        record.setUpdateDate(currentDate);
        sysUserDao.updateByPrimaryKeySelective(record);
    }

    @Override
    public TotalVO total() {
        TotalVO totalVO = new TotalVO();
        SysUserExample sysUserExample = new SysUserExample();
        totalVO.setTotal(sysUserDao.countByExample(sysUserExample));
        return totalVO;
    }
}
